<!--
 * @description  : 物流寄递-快递公司信息
 * @descriptionDetail: 物流寄递-快递公司信息
 * @copyright    : 浙江烟草
 * @author       : sy
 * @create       : 2022-09-09 18:31:01
-->
<template>
  <view class="page">
    <!-- #ifdef H5-ONLY -->
    <theme-navbar :isWhite="true" backText="返回" :title="typeInfo.typeName"></theme-navbar>
    <!-- #endif -->
    <view class="content">
      <view class="party-info-content">
        <view style="width: calc(100% + 30px);">
          <form-section title="基本信息"></form-section>
        </view>
        <view class="party-info-box">
          <u-form :model="caseExpressInfo" :rules="rules" :errorType="errorType" ref="uForm">
            <u-form-item label="快递公司名称" class="caseExpClass" :required="isRequired" prop="expressCompanyName" :label-position="labelPosition" ref="expressChangeRef">
              <auto-input v-if="typeInfo.type == 'add'" absIndex="1" :searchData="getExpressInfoList" absClass="caseExpClass" placeholder="请输入快递公司名称" v-model="caseExpressInfo.expressCompanyName" @choiceAutoItem="choiceAutoItem">
              </auto-input>
              <u-input
                v-else
                placeholder="请输入快递公司名称"
                v-model="caseExpressInfo.expressCompanyName"
              />
            </u-form-item>
            <u-form-item label="登记单位" :required="isRequired" prop="orgUuid" :label-position="labelPosition" right-icon="arrow-right">
              <u-input
                :disabled="true"
								:custom-style="pointerStyle"
                placeholder="请选择"
                v-model="caseExpressInfo.orgName"
                @click="orgSelectShow2 = true"
              >
              </u-input>
            </u-form-item>
            <u-form-item label="网点名称" :label-position="labelPosition">
              <u-input
                placeholder="请输入网点名称"
                v-model="caseExpressInfo.point"
              >
              </u-input>
            </u-form-item>
            <u-form-item label="法定代表人" :label-width="labelWidth">
              <u-input
                placeholder="请输入法定代表人"
                v-model="caseExpressInfo.legalPerson"
                input-align="right"
              >
              </u-input>
            </u-form-item>
            <u-form-item label="所在地" prop="place" :required="isRequired" :label-position="labelPosition">
              <view style="display: flex; flex-direction: column;width: 100%;">
                <u-input
                  type="select"
                  :disabled="true"
									:custom-style="pointerStyle"
                  placeholder="所在地行政区划选择"
                  v-model="caseExpressInfo.place"
                  @click=" (nativeNameSelectShow2 = true)"
                ></u-input>
                <u-line :color="$theme.u_border_color" style="margin: 10rpx 0;"></u-line>
                <u-row gutter="16">
                  <u-col span="12">
                    <u-input :border="true" placeholder="详细地址" v-model="caseExpressInfo.address"></u-input>
                  </u-col>
                </u-row>
              </view>
            </u-form-item>
            <u-form-item label="经纬度" :label-position="labelPosition">
              <u-input placeholder="请选择" v-model="caseExpressInfo.lonlat" :disabled="true"></u-input>
              <u-icon name="map-fill" :color="$theme.u_type_primary" size="44" @click="setLocation()"></u-icon>
            </u-form-item>
            <u-form-item label="联系方式" :label-width="labelWidth">
              <u-input
                placeholder="请输入联系方式"
                v-model="caseExpressInfo.contactPhone"
                input-align="right"
              >
              </u-input>
            </u-form-item>
            <u-form-item :label-width="labelWidth" label="状态" prop="statusName">
              <dic-input
                input-align="right"
                :keyWord="$u.dic.DIC_KEYS.S_SYS_IS_ACTIVE"
                :dicCode="caseExpressInfo.status"
                type="select"
                :border="border"
                :select-open="dicSelectOpen($u.dic.DIC_KEYS.S_SYS_IS_ACTIVE)"
                placeholder="请选择"
                v-model="caseExpressInfo.statusName"
                @changeInputModelData="(name)=>{$set(caseExpressInfo, 'statusName', name)}"
                @click="showDic($u.dic.DIC_KEYS.S_SYS_IS_ACTIVE,caseExpressInfo.status)"
              />
            </u-form-item>
            <u-form-item label="图片信息" :label-position="labelPosition">
              <view class="zk-img-content">
                <m-upload
                  :deletable="true"
                  :maxCount="picIds"
                  width="150rpx"
                  height="150rpx"
                  :file-list="fileList"
                  :multiple="true"
                  index="fileList"
                  :uploadParam="{'fiGroupCode':$FILE_GROUP_TYPE.c_case_express}"
                  upApiUrl="uploadBase64File"
                  ref="filePicUpload"
                  @on-list-change="changeUpload"
                >
                </m-upload>
              </view>
            </u-form-item>
          </u-form>
        </view>
      </view>
      <view class="space-content"></view>
      <view class="submit-btns btn-other-cls">
        <u-button class="u-btn" type="primary" @click="confirm">
          保存
        </u-button>
      </view>
      <!-- 组织机构选择 -->
      <u-popup mode="bottom" height="80%" v-model="orgSelectShow2">
        <org-select :cleanParentOrg="true" :isHybrid="true" limitNodeType="03" treeType="zm-comp" @choose="handlerChooseOrg('caseExpressInfo','orgSelectShow2',$event)"></org-select>
      </u-popup>
      <!-- 行政区选择 -->
      <u-popup mode="bottom" height="80%" v-model="nativeNameSelectShow2">
        <area-select @choose="nativeNameSelectShowComfir('caseExpressInfo','nativeNameSelectShow2',$event)"></area-select>
      </u-popup>
      <!-- 数据字典 -->
      <dic-choice
        :keyWord="dicKeyWords"
        :currentSelect="dicCurrentSelect"
        v-model="dicShow"
        @confirm="selectDicConfirm"
      ></dic-choice>
    </view>
  </view>
</template>

<script>
import caseService from '@/service/case/case.service.js';
import DicChoice from "@/components/dic_choice.vue";
import DicInput from "@/components/dic_input.vue";
import FormSection from "@/components/form-section.vue";
import OrgSelect from "@/components/org-select.vue";
import areaSelect from "@/components/area-select.vue";
import commonService from "@/service/common/common.service";
import AutoInput from "@/components/autoInput.vue";
import mUpload from '@/components/m-upload.vue';
export default {
  components:{
    DicChoice,
    DicInput,
    FormSection,
    OrgSelect,
    areaSelect,
    AutoInput,
    mUpload,
  },
  data(){
    return {
      errorType: ['border-bottom','message',],
      isRequired: true,
      labelPosition:"top",
      border: false,
      labelWidth:'360',
      caseExpressInfo:{ // 快递公司信息
        expressCompanyName:'',
      },
      rules:{
        expressCompanyName:[
          {
            required: true,
            message: "请输入快递公司名称",
            trigger: ["change",'blur',],
          },
        ],
        orgUuid:[
          {
            required: true,
            message: "请选择快递登记单位",
            trigger: ["change",'blur',],},
        ],
        place: [{
          required: true,
          message: '请选择所在地行政区划',
          // 可以单个或者同时写两个触发验证方式
          trigger: ["change",'blur',],
        },],
      },
      typeInfo:{},// 类型 添加/编辑
      orgSelectShow:false,
      orgSelectShow2:false,
      nativeNameSelectShow:false,
      nativeNameSelectShow2:false,
      dicShow: false, // dic_select 是否显示
      dicKeyWords: "", // dic 关键字
      dicCurrentSelect: "", // dic 当前选择项
      fileList: [],
      picIds: '20',
      prevParam:{},
			// h5端部分浏览器input设置disabled后点击事件失效 2023-10-26 fsx start
			pointerStyle: {
			  marginRight: "5px",
				pointerEvents: "none !important"
			},
			// h5端部分浏览器input设置disabled后点击事件失效 2023-10-26 fsx end
    }
  },
  onReady() {
    this.$refs.uForm.setRules(this.rules);
  },
  // 加载初始周期方法
  onLoad() {
    this.prevParam = this.getRouteParam();
    this.caseExpressInfo.caseUuid = this.prevParam.caseUuid;
    if (this.prevParam.type) {
      this.typeInfo.type = this.prevParam.type;
      this.typeInfo.typeName = this.prevParam.type == 'add' ? "添加快递公司" : "编辑快递公司";
    } else {
      this.typeInfo = {};
    }
    // 获取详情信息
    if(this.prevParam.param){
      this.caseExpressInfo = this.prevParam.param;
      this.caseExpressInfo.place = this.getPlaceName(this.caseExpressInfo.provCode,this.caseExpressInfo.cityCode,this.caseExpressInfo.countyCode);

      if (this.caseExpressInfo.photo) {
        let photoArr = this.caseExpressInfo.photo.split(',');
        photoArr.forEach((val) => {
          this.fileList.push({
            gfiId: val,
          });
        });
      }
    }

  },
  mounted(){

  },
  methods:{
    // 获取行政区划名称
    getPlaceName(placeProvCode,placeCityCode,placeCountyCode){
      let areaCoinNames = '';
      if(!this.$u.test.isEmpty(placeProvCode) && !this.$modal.isMuniCity(placeProvCode)){
        areaCoinNames = commonService.getPersonLocal(placeProvCode, true).areaName || "";
      }
      if(!this.$u.test.isEmpty(placeCityCode)){
        areaCoinNames += commonService.getPersonLocal(placeCityCode, true).areaName || "";
      }
      if(!this.$u.test.isEmpty(placeCountyCode)){
        areaCoinNames += commonService.getPersonLocal(placeCountyCode, true).areaName || "";
      }
      return areaCoinNames;
    },
    // 获取快递公司列表
    getExpressInfoList(txt) {
      return new Promise((resolve, reject) => {
        if (this.$u.test.isEmpty(txt)) {
          resolve([]);
          return;
        }
        caseService.getCaseExpressInfoList(txt, 1, 20).then(res => {
          res.data.forEach(itm => {
            itm.name = itm.orgName ? [itm.expressCompanyName,].join("") + ' - ' + itm.orgName : [itm.expressCompanyName,].join("");
          });
          resolve(res.data);
        }).catch(er => {
          resolve([]);
        });
      });
    },
    // 获取自定选择的数据（物流公司名称 或 快递公司名称）
    choiceAutoItem(itm, index){
      if(index == '1'){
        this.caseExpressInfo =  {... itm,};
        this.caseExpressInfo.place = this.getPlaceName(this.caseExpressInfo.provCode,this.caseExpressInfo.cityCode,this.caseExpressInfo.countyCode);
      }
    },
    // 登记单位
    handlerChooseOrg(type,isShow,orgs) {
      if(orgs.length > 0){
        this[type].orgUuid = orgs[0].id;
        this[type].orgName = orgs[0].name;
      }
      this[isShow] = false;
    },
    // 城市
    nativeNameSelectShowComfir(type,isShow,areas) {
      if(this.$modal.isMuniCity(areas[0].proCode)){
        this[type].place = [areas[0].admdivName, areas[0].countryName,].join("");
      }else{
        this[type].place = [areas[0].proName, areas[0].admdivName, areas[0].countryName,].join("");
      }
      this[type].provCode = areas[0].proCode;
      this[type].cityCode = areas[0].admdivCode;
      this[type].countyCode = areas[0].countryCode;
      this[isShow] = false;
    },
    // 数据字典组件选择事件
    dicSelectOpen: function (keyWords) {
      if (this.dicKeyWords == keyWords && this.dicShow) {
        return true;
      }
      return false;
    },
    showDic: function (key, cur) {
      if (this.dicShow) return;
      this.dicKeyWords = key;
      this.dicCurrentSelect = cur;
      this.dicShow = true;
    },
    selectDicConfirm: function (e) {
      if(this.dicKeyWords == this.$u.dic.DIC_KEYS.S_SYS_IS_ACTIVE) {
        // 状态
        this.caseExpressInfo.statusName = e[0].label;
        this.caseExpressInfo.status = e[0].extra.bcbCode;
      }
    },
    // 经纬度
    setLocation() {
      let self = this;
      // #ifdef H5-DINGDING
      this.$deviceApi
        .getLocationByMap(this.caseExpressInfo.gisY, this.caseExpressInfo.gisX)
        .then((latlng) => {
          self.$set(self.caseExpressInfo, "lonlat", `${latlng[1]},${latlng[0]}`);
          self.$set(self.caseExpressInfo, "gisX",latlng[1]);
          self.$set(self.caseExpressInfo, "gisY", latlng[0]);
        })
        .catch((err) => {
          self.$api.toast("获取位置信息失败");
        });
      // #endif

      // #ifndef H5-DINGDING
      this.$u.route("pages/commonPage/modifyLocationMap");
      // #endif
    },
    // 数据返回操作
    updateBackState(obj) {
      let self = this;
      // 经纬度
      if (obj.pos) {
        self.$set(self.caseExpressInfo, "lonlat", `${obj.pos.longitude},${obj.pos.latitude}`);
        self.$set(self.caseExpressInfo, "gisX", obj.pos.longitude);
        self.$set(self.caseExpressInfo, "gisY", obj.pos.latitude);
      }
    },
    // 快递公司信息 表单验证
    validForm() {
      let basicValid = false;
      this.$refs.uForm.validate(valid => {
        if (valid) {
          basicValid = true;
          console.log('表单验证通过');
        } else {
          basicValid = false;
          console.log('表单验证失败');
        }
      });
      return basicValid;
    },
    // 确认
    confirm(){
      let self = this;
      // 验证表单
      let flag = this.validForm();
      let ids = [];
      if (flag) {
        if(this.fileList.length > 0){
          this.fileList.forEach((item) => {
            ids.push(item.gfiId);
          });
          this.caseExpressInfo.photo = ids.join(',');
        }
        this.$u.loading('数据保存中...');
        this.caseExpressInfo.caseUuid = this.prevParam.caseUuid;
        if (this.caseExpressInfo.uniqueKey) {
          delete this.caseExpressInfo.uniqueKey
        }
        caseService.saveOrUpdateExpress(this.caseExpressInfo).then(res => {
          this.$u.hideLoading();
          if(res.success){
            this.$u.toast(res.msg);
            self.backPrev({
              paramKey: "formItem",
              param :{
                type:'express',
              },
            });
          }else{
            this.$u.toast(res.msg);
          }
        }).catch(err => {
          this.$u.toast(err);
          this.$u.hideLoading();
        })
      }
    },
    // 上传/删除图片事件
    changeUpload(list, key) {
      if (list.length > 0) {
        this.fileList = [...list,];
      } else {
        this.fileList = [];
      }
    },

  },
}
</script>

<style lang="scss" scoped>
@import "../case_common.scss";
.page{ padding:0; }
</style>
